package com.cskaoyan.service.impl;

import com.cskaoyan.bean.vo.AdParameter;
import com.cskaoyan.bean.PageData;
import com.cskaoyan.bean.PageParameter;
import com.cskaoyan.mapper.MarketAdMapper;
import com.cskaoyan.model.MarketAd;
import com.cskaoyan.model.MarketAdExample;
import com.cskaoyan.service.AdService;
import com.cskaoyan.utils.MyBatisUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;

public class AdServiceImpl implements AdService {


    @Override
    public PageData list(PageParameter parameter) {
        AdParameter adParameter = (AdParameter) parameter;
        // 分页
        PageHelper.startPage(parameter.getPage(), parameter.getLimit());

        MarketAdExample example = new MarketAdExample();
        example.setOrderByClause(parameter.getSort() + " " + parameter.getOrder());
        MarketAdExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);

        if (adParameter.getName() != null && !"".equals(adParameter.getName())) {
            criteria.andNameLike("%" + adParameter.getName() + "%");
        }

        if (adParameter.getContent() != null && !"".equals(adParameter.getContent())) {
            criteria.andContentLike("%" + adParameter.getContent() + "%");
        }
        // 连接数据库
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketAdMapper mapper = sqlSession.getMapper(MarketAdMapper.class);
        List<MarketAd> marketAds = mapper.selectByExample(example);
        sqlSession.close();

        PageData data = PageData.list(marketAds);
        return data;
    }

    @Override
    public void create(MarketAd marketAd) {

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        marketAd.setAddTime(new Date());
        marketAd.setUpdateTime(new Date());

        MarketAdMapper mapper = sqlSession.getMapper(MarketAdMapper.class);
        mapper.insertSelective(marketAd);

        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void update(MarketAd marketAd) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        marketAd.setUpdateTime(new Date());
        marketAd.setAddTime(new Date());

        MarketAdMapper mapper = sqlSession.getMapper(MarketAdMapper.class);
        mapper.updateByPrimaryKeySelective(marketAd);


        sqlSession.commit();
        sqlSession.close();

    }

    @Override
    public void delete(MarketAd marketAd) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketAdMapper mapper = sqlSession.getMapper(MarketAdMapper.class);
        marketAd.setDeleted(true);
        mapper.updateByPrimaryKeySelective(marketAd);

        sqlSession.commit();
        sqlSession.close();
    }
}
